package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.PageResult;
import com.woniu.mapper.*;
import com.woniu.pojo.*;
import com.woniu.pojo.Package;
import com.woniu.service.ISignService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author doujiao
 * @since 2022-10-14
 */
@Service
public class SignServiceImpl extends ServiceImpl<SignMapper, Sign> implements ISignService {
    @Resource
    private SignMapper signMapper;
    @Resource
    private LabelMapper labelMapper;
    @Resource
    private UserLabelMapper userLabelMapper;
    @Resource
    private UserDetailMapper userDetailMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrganizationMapper organizationMapper;
    @Resource
    private TeamMapper teamMapper;
    @Resource
    private DoctorMapper doctorMapper;
    @Resource
    private PackageMapper packageMapper;
    @Resource
    private UserSignStatusMapper userSignStatusMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 条件分页查询签约
     * @param currentPage
     * @param pageSize
     * @param querySignVo
     * @return
     */
    public PageResult queryByPage(Long currentPage, Long pageSize, QuerySignVo querySignVo) {
        //构建分页
        IPage<Sign> iPage=new Page(currentPage,pageSize);
        PageResult pageResult = new PageResult();
        QueryWrapper<Sign> wrapper = new QueryWrapper<>();
        //wrap
        wrapper.between("status","0","3");
        if (querySignVo!=null){
            //标签
            if (querySignVo.getSignStatusId()!=null && querySignVo.getSignStatusId()>0){
               wrapper.eq("sign_status_id",querySignVo.getSignStatusId());
            }
            if (querySignVo.getTeamId()!=null && querySignVo.getTeamId()>0 ){
                wrapper.eq("team_id",querySignVo.getTeamId());
            }
            if (querySignVo.getOrganizationId()!=null && querySignVo.getOrganizationId()>0){
                wrapper.eq("organization_id",querySignVo.getOrganizationId());
            }
            if ( querySignVo.getPackageId()!=null && querySignVo.getPackageId()>0 ){
                wrapper.eq("package_id",querySignVo.getPackageId());
            }
            if (querySignVo.getCreateTime()!=null){
                wrapper.gt("create_time",querySignVo.getCreateTime());
            }
            if (querySignVo.getName()!=null&&querySignVo.getName().length()>0){
                QueryWrapper<User> wrapperUser = new QueryWrapper<>();
                wrapperUser.like("name",querySignVo.getName());
                List<User> users = userMapper.selectList(wrapperUser);
                for (User user : users) {
                    Long userId = user.getId();
                    wrapper.eq("user_id",userId);
                }
            }
            IPage<Sign> page = signMapper.selectPage(iPage, wrapper);
            List<Sign> signs = page.getRecords();
            pageResult.setTotal(page.getTotal());
            List<SignVo> signVoList=new ArrayList<>();
            for (Sign sign : signs) {
                SignVo signVo = new SignVo();
                SignVo signVo1 = signToSignVo(sign, signVo);
                signVoList.add(signVo1);
            }
            pageResult.setData(signVoList);
            return pageResult;
        }

        IPage<Sign> page = signMapper.selectPage(iPage, null);
        List<Sign> signs = page.getRecords();
        pageResult.setTotal(page.getTotal());
        List<SignVo> signVoList=new ArrayList<>();
        for (Sign sign : signs) {
            SignVo signVo = new SignVo();
            SignVo signVo1 = signToSignVo(sign, signVo);
            signVoList.add(signVo1);
        }
        pageResult.setData(signVoList);
        return pageResult;
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public SignVo queryById(Long id) {
        SignVo signVo = new SignVo();
        Sign sign = signMapper.selectById(id);
        SignVo signVo1 = signToSignVo(sign, signVo);
        return signVo1;
    }

    /**
     * 编辑
     * @param signEditVo
     * @return
     */
    public Boolean edit(SignEditVo signEditVo) {
        //修改签约表
        //修改用户
        //根据id查询sign
        Long signId = signEditVo.getId();
        Sign sign = signMapper.selectById(signId);
        //复制
        BeanUtils.copyProperties(signEditVo,sign);
        //根据sign的userid查询用户
        Long userId1 = sign.getUserId();
        User user = userMapper.selectById(userId1);
        Long userId2 = user.getId();
        BeanUtils.copyProperties(signEditVo,user);
        //设置回去
        user.setId(userId2);
        user.setId(sign.getUserId());
        //根据userid查询userdetail
        QueryWrapper<UserDetail> userDetailQueryWrapper = new QueryWrapper<>();
        userDetailQueryWrapper.eq("user_id",user.getId());
        UserDetail userDetail = userDetailMapper.selectOne(userDetailQueryWrapper);
        //拿到id和user_id
        Long id = userDetail.getId();
        Long userId = userDetail.getUserId();
        BeanUtils.copyProperties(signEditVo,userDetail);
        //设置回去
        userDetail.setId(id);
        userDetail.setUserId(userId);
        signMapper.updateById(sign);
        userMapper.updateById(user);
        userDetailMapper.updateById(userDetail);
        return true;
    }

    /**
     * 分页查询签约记录的数据
     * @param currentPage
     * @param pageSize
     * @param querySignRecordVo
     * @return
     */
    public PageResult queryRecordByPage(Long currentPage, Long pageSize, QuerySignRecordVo querySignRecordVo) {
        //构建分页
        IPage<Sign> iPage=new Page(currentPage,pageSize);
        PageResult pageResult = new PageResult();
        //wrap
        QueryWrapper<Sign> wrapper = new QueryWrapper<>();
        wrapper.between("status","4","5");
        if (querySignRecordVo!=null) {

            //状态
            if (querySignRecordVo.getStatus() != null&& querySignRecordVo.getStatus().length()>0 ) {
                wrapper.eq("status", querySignRecordVo.getStatus());
            }
            //团队
            if (querySignRecordVo.getTeamId() != null && querySignRecordVo.getTeamId() > 0) {
                wrapper.eq("team_id", querySignRecordVo.getTeamId());
            }
            //机构
            if (querySignRecordVo.getOrganizationId() != null && querySignRecordVo.getOrganizationId() > 0) {
                wrapper.eq("organization_id", querySignRecordVo.getOrganizationId());
            }
            //服务包
            if (querySignRecordVo.getPackageId() != null && querySignRecordVo.getPackageId() > 0) {
                wrapper.eq("package_id", querySignRecordVo.getPackageId());
            }
            //申请时间
            if (querySignRecordVo.getApplyTime() != null) {
                wrapper.gt("create_time", querySignRecordVo.getApplyTime());
            }
            //名字
            if (querySignRecordVo.getName() != null && querySignRecordVo.getName().length() > 0) {
                QueryWrapper<User> wrapperUser = new QueryWrapper<>();
                wrapperUser.like("name", querySignRecordVo.getName());
                List<User> users = userMapper.selectList(wrapperUser);
                for (User user : users) {
                    Long userId = user.getId();
                    wrapper.eq("user_id", userId);
                }
            }
            IPage<Sign> page = signMapper.selectPage(iPage, wrapper);
            List<SignRecordVo> signRecordVoList=new ArrayList<>();
            List<Sign> signs = page.getRecords();
            for (Sign sign : signs) {
                SignRecordVo signRecordVo = new SignRecordVo();
                SignRecordVo signRecordVo1 = signToSignRecordVo(sign, signRecordVo);
                signRecordVoList.add(signRecordVo1);
            }
            pageResult.setTotal(page.getTotal());
            pageResult.setData(signRecordVoList);
            return pageResult;
        }
        IPage<Sign> page = signMapper.selectPage(iPage, wrapper);
        List<SignRecordVo> signRecordVoList=new ArrayList<>();
        List<Sign> signs = page.getRecords();
        for (Sign sign : signs) {
            SignRecordVo signRecordVo = new SignRecordVo();
            SignRecordVo signRecordVo1 = signToSignRecordVo(sign, signRecordVo);
            signRecordVoList.add(signRecordVo1);
        }
        pageResult.setTotal(page.getTotal());
        pageResult.setData(signRecordVoList);
        return pageResult;
    }

    /**
     * 根据id查看记录
     * @param id
     * @return
     */
    public SignRecordVo queryRecordById(Long id) {
        SignRecordVo signRecordVo = new SignRecordVo();
        Sign sign = signMapper.selectById(id);
        SignRecordVo signRecordVo1 = signToSignRecordVo(sign, signRecordVo);
        return signRecordVo1;
    }

    /**
     * 编辑record
     * @param signRecordEditVo
     * @return
     */
    public Boolean editRecord(SignRecordEditVo signRecordEditVo) {
        //修改签约表
        //修改用户
        //根据id查询sign
        Long signId = signRecordEditVo.getId();
        Sign sign = signMapper.selectById(signId);
        //复制
        BeanUtils.copyProperties(signRecordEditVo,sign);
        //根据sign的userid查询用户
        Long userId1 = sign.getUserId();
        User user = userMapper.selectById(userId1);
        Long userId2 = user.getId();
        BeanUtils.copyProperties(signRecordEditVo,user);
        //设置回去
        user.setId(userId2);
        user.setId(sign.getUserId());
        //根据userid查询userdetail
        QueryWrapper<UserDetail> userDetailQueryWrapper = new QueryWrapper<>();
        userDetailQueryWrapper.eq("user_id",user.getId());
        UserDetail userDetail = userDetailMapper.selectOne(userDetailQueryWrapper);
        //拿到id和user_id
        Long id = userDetail.getId();
        Long userId = userDetail.getUserId();
        BeanUtils.copyProperties(signRecordEditVo,userDetail);
        //设置回去
        userDetail.setId(id);
        userDetail.setUserId(userId);
        signMapper.updateById(sign);
        userMapper.updateById(user);
        userDetailMapper.updateById(userDetail);
        return true;

    }

    /**
     * 审核通过
     * @param signRecordEditVo
     * @return
     */
    public Boolean passAudit(SignRecordEditVo signRecordEditVo) {
        //修改状态(支付)和设计时间
        Long id = signRecordEditVo.getId();
        Sign sign = signMapper.selectById(id);
        Date date = new Date();

        sign.setPayTime(date);
        BeanUtils.copyProperties(signRecordEditVo,sign);
        sign.setStatus("1");
        //未支付，等待支付
        sign.setSignStatusId(6L);
        int updateById = signMapper.updateById(sign);
        //清除审核的redis
        stringRedisTemplate.delete("audit"+id);
        if (updateById<0){
            return false;
        }
        //设置定时10分，如果长时间间未支付，设置为过期
        stringRedisTemplate.opsForValue().set("payTime"+id, "已支付", 60 * 10, TimeUnit.SECONDS);
        return true;

    }

    /**
     * 驳回
     * @param signRecordEditVo
     * @return
     */
    public Boolean refuse(SignRecordEditVo signRecordEditVo) {
        Long id = signRecordEditVo.getId();
        Sign sign = signMapper.selectById(id);
        //变回驳回
        sign.setStatus("3");
        sign.setSignStatusId(3L);
        int updateById = signMapper.updateById(sign);
        if (updateById<0){
            return false;
        }
        return true;
    }


    /**
     * 转换2
     * * @param sign
     *      * @param signRecordVo
     */
    public SignRecordVo signToSignRecordVo(Sign sign,SignRecordVo signRecordVo){
        BeanUtils.copyProperties(sign,signRecordVo);
        //user
        User user = userMapper.selectById(sign.getUserId());
        BeanUtils.copyProperties(user,signRecordVo);
        //由于复制用户id被覆盖了
        signRecordVo.setId(sign.getId());
        //用户详情
        QueryWrapper<UserDetail> userDetailQueryWrapper = new QueryWrapper<>();
        userDetailQueryWrapper.eq("user_id",user.getId());
        //现居住地址
        UserDetail userDetail = userDetailMapper.selectOne(userDetailQueryWrapper);
        String addressNow = userDetail.getAddressNow();
        signRecordVo.setAddressNow(addressNow);
        //由于复制用户id被覆盖了
        signRecordVo.setId(sign.getId());
        //签约状态
        String status = sign.getStatus();
        if ("4".equals(status)){
            signRecordVo.setSignStatus("生效中");
        }else {
            signRecordVo.setSignStatus("已过期");
        }
        //标签
        QueryWrapper<UserLabel> userLabelWrapper = new QueryWrapper<>();
        userLabelWrapper.eq("user_id",user.getId());
        List<UserLabel> userLabels = userLabelMapper.selectList(userLabelWrapper);
        List<Label> labelList=new ArrayList<>();
        for (UserLabel userLabel : userLabels) {
            Long labelId = userLabel.getLabelId();
            Label label = labelMapper.selectById(labelId);
            labelList.add(label);
        }
        signRecordVo.setLabelList(labelList);
        //机构
        Organization organization = organizationMapper.selectById(sign.getOrganizationId());
        signRecordVo.setOrganizationName(organization.getName());
        //团队
        Team team = teamMapper.selectById(sign.getTeamId());
        signRecordVo.setTeamName(team.getName());
        //服务包
        Package aPackage = packageMapper.selectById(sign.getPackageId());
        signRecordVo.setPackageName(aPackage.getName());
        //花费
        BigDecimal price = aPackage.getPrice();
        signRecordVo.setCost(price);
        //医生
        Doctor doctor = doctorMapper.selectById(sign.getDoctorId());
        signRecordVo.setDoctorName(doctor.getName());
        signRecordVo.setStatus(sign.getStatus());
        return signRecordVo;
    }

    /**
     * 转换
     * @param sign
     * @param signVo
     * @return
     */
    public SignVo signToSignVo(Sign sign,SignVo signVo){
        BeanUtils.copyProperties(sign,signVo);
        signVo.setApplyTime(sign.getApplyTime());
        //user
        User user = userMapper.selectById(sign.getUserId());

        BeanUtils.copyProperties(user,signVo);
        signVo.setId(sign.getId());
        //用户详情
        QueryWrapper<UserDetail> userDetailQueryWrapper = new QueryWrapper<>();
        userDetailQueryWrapper.eq("user_id",user.getId());
        //现居住地址
        UserDetail userDetail = userDetailMapper.selectOne(userDetailQueryWrapper);
        String addressNow = userDetail.getAddressNow();
        signVo.setAddressNow(addressNow);
        //签约状态
        Long signStatusId = sign.getSignStatusId();
        UserSignStatus userSignStatus = userSignStatusMapper.selectById(signStatusId);
        signVo.setSignStatus(userSignStatus.getName());
        //标签
        QueryWrapper<UserLabel> userLabelWrapper = new QueryWrapper<>();
        userLabelWrapper.eq("user_id",user.getId());
        List<UserLabel> userLabels = userLabelMapper.selectList(userLabelWrapper);
        List<Label> labelList=new ArrayList<>();
        for (UserLabel userLabel : userLabels) {
            Long labelId = userLabel.getLabelId();
            Label label = labelMapper.selectById(labelId);
            labelList.add(label);
        }
        signVo.setLabelList(labelList);
        //机构
        Organization organization = organizationMapper.selectById(sign.getOrganizationId());
        signVo.setOrganizationName(organization.getName());
        //团队
        Team team = teamMapper.selectById(sign.getTeamId());
        signVo.setTeamName(team.getName());
        //服务包
        Package aPackage = packageMapper.selectById(sign.getPackageId());
        signVo.setPackageName(aPackage.getName());
        //花费
        BigDecimal price = aPackage.getPrice();
        signVo.setCost(price);
        //医生
        Doctor doctor = doctorMapper.selectById(sign.getDoctorId());
        signVo.setDoctorName(doctor.getName());
        return signVo;
    }
}
